<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次编号" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="溯源码" prop="tracingCode">
        <el-input
          v-model="queryParams.tracingCode"
          placeholder="请输入溯源码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="stratTime">
        <el-date-picker clearable
                        v-model="queryParams.stratTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
                        v-model="queryParams.endTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效期" prop="days">
        <el-input
          v-model="queryParams.days"
          placeholder="请输入有效期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="农户名称" prop="farmerName">
        <el-input
          v-model="queryParams.farmerName"
          placeholder="请输入农户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:products:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:products:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:products:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编号" align="center" prop="productId" />
      <el-table-column label="产物名称" align="center" prop="goodsName" />
      <el-table-column label="批次编号" align="center" prop="materialCode" />
      <el-table-column label="溯源码" align="center" prop="tracingCode" />
      <el-table-column label="创建时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="days" />
      <el-table-column label="农户名称" align="center" prop="farmerName" />
      <el-table-column label="地址" align="center" prop="address"  width="180"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status==='0'" size="small" type="success">未出/入库</el-tag>
          <el-tag v-if="scope.row.status==='1'" size="small" type="success">已出库</el-tag>
          <el-tag v-if="scope.row.status==='2'" size="small" type="success">已入库</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:products:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:products:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="materialCode">
              <el-checkbox-group v-model="form.gids">
                <el-checkbox  v-for="g in goods"
                              :key="g.goodsId"
                              :label="g.goodsId">{{g.goodsName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="批次编号" prop="materialLotId">
              <el-select v-model="form.materialLotId" placeholder="批次编号">
                <el-option
                  v-for="item in materialLots"
                  :key="item.materialLotId"
                  :label="item.materialCode"
                  :value="item.materialLotId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="timeValue"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                :picker-options="pickerOptions"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="getDays"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="溯源码" prop="tracingCode">
              <el-input v-model="form.tracingCode" placeholder="请输入溯源码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期" prop="days">
              <el-input v-model="form.days" placeholder="请输入有效期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="省/市/县">
              <el-cascader
                v-model="cityValue"
                :options="options"
                :props="cityProps"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="农户名称" prop="farmerName">
              <el-select v-model="form.farmerId" placeholder="批次编号">
                <el-option
                  v-for="item in farmers"
                  :key="item.farmerId"
                  :label="item.farmerName"
                  :value="item.farmerId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产物备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入产物备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct,getHuiGoods, getProduct, delProduct, addProduct, updateProduct,getGoods,selectDays,getFarmerList,getMaterialLotList} from "@/api/product/products";
import {cityTreeSelect} from "@/api/crop/products";

export default {
  name: "index",
  data() {
    return {
      // 遮罩层
      cityValue: [],
      options: [],
      cityProps:{
        value:"id",
        label:"name",
      },
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      farmers: [],
      goods: [],
      materialLots: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      daysTime:undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        tracingCode: null,
        stratTime: null,
        endTime: null,
        days: null,
        farmerName: null,
        xid: null,
        yid: null,
        zid: null,
        status: null,
      },
      // 表单参数
      form: {gids:[]},
      // 表单校验
      rules: {
      },
      timeValue: [],
      gids:[],
      time1: "",
      time2: "",
      pickerOptions:{
        disabledDate(time){
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询城市列表 */
    cityList(){
      cityTreeSelect().then(r=>{
        this.options=r.data;
      })
    },
    handleChange(value) {
      console.log(value);
      if(value!=null&&value.length>0){
        this.form.xid=value[value.length-3];
        this.form.yid=value[value.length-2];
        this.form.zid=value[value.length-1];
      }
    },
    getDays(){
      let one = this.timeValue[0];
      let two = this.timeValue[1];
      selectDays(one,two).then(r=>{
        this.form.days=r.data;
        console.log(this.form.days);
      })
    },
    /** 查询农户列表 */
    selectGoods(){
      getGoods().then(response => {
        this.goods = response.data;
      });
    },
    /** 查询农户列表 */
    selectFarmerList(){
      getFarmerList().then(response => {
        this.farmers = response.data;
      });
    },
    /** 查询批次号列表 */
    selectMaterialLotList(){
      getMaterialLotList().then(response => {
        this.materialLots = response.data;
      });
    },
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.form = {};
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form={gids:[]};
      this.cityList();
      this.selectGoods();
      this.selectFarmerList();
      this.selectMaterialLotList();
      this.timeValue=[];
      this.open = true;
      this.title = "添加产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form={gids:[]};
      this.selectGoods();
      this.timeValue=[];
      this.cityValue=[];
      this.cityList();
      this.selectFarmerList();
      this.selectMaterialLotList();
      this.timeValue.push(row.startTime);
      this.timeValue.push(row.endTime);
      this.cityValue.push(row.xid+'');
      this.cityValue.push(row.yid+'');
      this.cityValue.push(row.zid+'');
      const productId = row.productId || this.ids;
      this.selectHuiGoods(productId);
      getProduct(productId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品";
      });
    },
    selectHuiGoods(productId){
      getHuiGoods(productId).then(r=>{
        this.form.gids=r.data;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            this.form.startTime=this.timeValue[0];
            this.form.endTime=this.timeValue[1];
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.startTime=this.timeValue[0];
            this.form.endTime=this.timeValue[1];
            // alert(JSON.stringify(this.form))
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除产品编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crop/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
